package com.springframework.context;


import com.springframework.annotation.Autowired;
import com.springframework.annotation.Component;
import com.springframework.annotation.ComponentScan;
import com.springframework.beans.factory.BeanDefinition;
import com.springframework.annotation.Scope;

import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;



/**
 * ClassName: OneApplicationContext
 * Description:
 *
 * @author: zsg
 * @Create 2024/6/2 16:47
 */
public class OneApplicationContext {
    private Class<?> configClass;

    //单例池
    private ConcurrentHashMap<String, Object> singletonObejcts = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    public OneApplicationContext(Class<?> configClass){
        // 初始化
        this.configClass = configClass;
        scan(configClass);
        // 实例化
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            if (beanDefinition.getScope().equals(Scope.SINGLETON)){
                Object bean = createBean(beanDefinition);
                singletonObejcts.put(beanName, bean);
            }
        });
        // 注册

        // 初始化

        // 返回
    }

    /**
     * 扫描配置文件
     * @param configClass
     */
    private void scan(Class<?> configClass) {
        ComponentScan componentScan = configClass.getDeclaredAnnotation(ComponentScan.class);
        String scanPath = componentScan.value();
        // 扫描
        ClassLoader classLoader = OneApplicationContext.class.getClassLoader();
        scanPath = scanPath.replace(".", "/");
        URL resource = classLoader.getResource(scanPath);
        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    String className = fileName.substring(fileName.indexOf("com"), fileName.lastIndexOf("."));
                    className = className.replace("\\", ".");
                    try {
                        Class<?> clazz = classLoader.loadClass(className);
                        if (clazz.isAnnotationPresent(Component.class)){
                            // 获取注解
                            //解析类，判断当前bean是单例bean，还是原型bean
                            //BeanDefinition
                            Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String beanName = componentAnnotation.value();
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);

                            if (clazz.isAnnotationPresent(Scope.class)){
                                Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());

                            } else {
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName, beanDefinition);
                            // 实例化

                            // 注册
                            // 初始化
                            // 返回
                        }

                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Object getBean(String beanName){
        if (beanDefinitionMap.containsKey(beanName)){//能否在beanDefinitionMap中找到bean
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")){//是否是单例bean
                if (singletonObejcts.containsKey(beanName)){//是否已经创建存在于单例池中
                    return singletonObejcts.get(beanName);
                } else {
                    Object bean = createBean(beanDefinition);
                    singletonObejcts.put(beanName, bean);
                    return bean;
                }
            } else {
                return createBean(beanDefinition);
            }
        } else {
            throw new RuntimeException("bean not found");
        }

    }

    private Object createBean(BeanDefinition beanDefinition) {

        Class<?> clazz = beanDefinition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();
            //简单的依赖注入，后续需要解决循环依赖
            //获取了 beanDefinition 类的 Class 对象，然后使用 getDeclaredField 方法获取了名为 "field" 的私有字段。
            // 接着，我们使用 setAccessible(true)方法关闭了访问修饰符的检查.
            // 然后使用 set 方法给这个字段设置了一个值。
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Autowired.class)){
                    Object bean = getBean(field.getName());
                    field.setAccessible(true);
                    field.set(instance, bean);
                }
            }
            return instance;
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
